from common.log_info import Logger
import traceback
import pymysql
from common.config import *


class DButil:
    _conn = None  # 数据库连接对象

    @classmethod
    def get_conn(cls, env):
        """获取数据库连接对象"""
        host_db = getconf(env, "host_db")
        user_db = getconf(env, "user_db")
        password_db = getconf(env, "password")
        port_db = getconf(env, "port")
        if cls._conn is None:
            cls._conn = pymysql.connect(host=host_db, port=int(port_db), user=user_db,
                                        password=password_db,
                                        database="buorg_coupon",
                                        autocommit=True, charset="utf8")
        return cls._conn

    @classmethod
    def close_conn(cls):
        """关闭数据库连接"""
        if cls._conn:
            cls._conn.close()
            cls._conn = None

    @classmethod
    def get_cursor(cls, env):
        """获取游标对象"""
        return cls.get_conn(env).cursor(pymysql.cursors.DictCursor)

    @classmethod
    def close_cursor(cls, cursor):
        """关闭游标对象"""
        if cursor:
            cursor.close()

    @classmethod
    def get_sql_info(cls, env, sql):
        """执行sql语句"""
        data = None
        cursor = None
        try:
            cursor = cls.get_cursor(env)
            cursor.execute(sql)
            data = cursor.fetchall()  # 返回多个元组，多条记录
        except Exception as e:
            Logger("coupon", "sql_coupon").logger.info(f"get_one error:{e}")
            traceback.print_exc()
        finally:
            cls.close_cursor(cursor)
            cls.close_conn()
        return data


if __name__ == '__main__':
    DButil.get_sql_info("test", "select *  from coupon_base_info;")
